<?php

namespace app\admin\controller\vactivities;

use app\admin\model\vactivities\Ticket;
use app\common\controller\Backend;
use Exception;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 活动管理
 *
 * @icon fa fa-circle-o
 */
class Serimange extends Backend
{
    
    /**
     * Serimange模型对象
     * @var \app\admin\model\vactivities\Activity
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\vactivities\Activity;
        $this->view->assign("isrecordingList", $this->model->getIsrecordingList());
        $this->catemodel = new \app\admin\model\superdata\Activitycategory;
        $this->tagsmodel = new \app\admin\model\superdata\Activitytags;
        $this->tmodel = new \app\admin\model\vactivities\Ticket;
        $this->seriesmodel = new \app\admin\model\vactivities\Seriesactivity;
        $this->view->assign('categoryList',$this->catemodel->getCategoryList());
        $this->view->assign('AtagsList',$this->tagsmodel->getAtagsList());
        $this->view->assign('seriesList',$this->seriesmodel->getSeriesList($this->auth->id));

        $this->view->assign('headingList', $this->model->getHeadingList(2));
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        $pack_id = $this->request->param("pack_id");
        $m = [];
        if(!$pack_id){
            $this->error(__('Params err'));
        }else{
            $m["series_id"] = $pack_id;
        }
        $mywhere['admin_id'] = $this->auth->id;
        $tag = $this->request->param('tag');
        $nowTime = time();
        if(!empty($tag)){
            if($tag == $this->model::ACTIVITY_TAG_1){
                $map = ['startTime'=>['gt',$nowTime],'status'=>['neq',2]];//<=
            }else if($tag == $this->model::ACTIVITY_TAG_2){
                $map = ['startTime'=>['elt',$nowTime],'status'=>['neq',2]];//>
            }else if ($tag == $this->model::ACTIVITY_TAG_3){//回收站
                $map = ['status'=>['eq',2]];
            }
        }else{
            $tag = 1;
            $map = ['startTime'=>['gt',$nowTime],'status'=>['neq',2]];
        }

        //print_r($map);
       // print_r($m);
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->where($map)
                    ->where($m)
                    ->where($where)
                    ->where($mywhere)
                    ->order($sort, $order)
                    ->paginate($limit);
            foreach ($list as $row) {
                $row->visible(['id','name','serial','createTime','startTime','duration','category','tags','isrecording','series_id','status']);
                $row['tags'] = $this->tagsmodel->getTagsNameById($row['tags']);
                $row['category'] = $this->catemodel->getcateNameById($row['category']);
                $row['series_id'] = $this->seriesmodel->getseriesNameById($row['series_id']);
                $row['duration'] = s_to_hs($row['duration']);
                $row['nowTime'] = $nowTime;//自定义一个当前时间
                
            }
            unset($mywhere);
            unset($map);
            unset($m);
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $this->view->assign('now_function', 'vactivities/serimange/index');
        $this->view->assign("tag", $tag);
        $this->view->assign("pack_id", $pack_id);
        $this->assignconfig('pack',['sid' =>$pack_id]);
        return $this->view->fetch();
    }



    public function add()
    {

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params['admin_id'] = $this->auth->id;
            $params['serial'] = nonceStr();
            if($params['duration']==0){
                $this->error(__('时长不能为0'));
            }
            $params['duration'] = (int)$params['duration'] * 60;
            $params['startTime'] = strtotime($params['startTime']);
            $params['link_url'] = trim($params['link_url']);
            $tmodel = new \app\admin\model\vactivities\Ticket;
            //$params['endTime'] = 0;
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                $t = [];
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    $count = count(array_filter($params['ticket_name']));
                    if($count == 0){
                        $count = count(array_filter($params['ticket_price']));
                    }

                    if($count > 0){//添加入场卷
                        for($i = 0;$i < $count;$i++){
                            if($params['ticket_price'][$i]==0 || $params['ticket_price'][$i]==0.00){
                                $params['ticket_name'][$i] = 'VIP入场券';
                            }
                            $t[] = [
                                'name'=>$params['ticket_name'][$i],
                                'price'=> priceyuantofen($params['ticket_price'][$i]),
                                'number'=>$params['ticket_number'][$i],
                                'activity_id'=>$this->model->id,
                                'type'=>Ticket::TICKET_TYPE_2,
                                'admin_id'=>$this->auth->id,
                                'createTime' => date('Y-m-d H:i:s',time())
                            ];

                        }
                        $count = count(array_filter($t));
                        if($count > 0 ){
                            $this->tmodel->insetAll($t);
                        }

                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        $this->view->assign('pack_id',$this->request->get('pack_id'));
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        $row['duration'] = s_to_hs($row['duration']);
        $row['startTime'] = date('Y-m-d H:i:s',$row['startTime']);
        $tmodel = new \app\admin\model\vactivities\Ticket;
        $tlist = $tmodel->getTicketList($ids,Ticket::TICKET_TYPE_2,'');
        $row['tlist'] = isset($tlist) ? json_encode($tlist, JSON_UNESCAPED_UNICODE) : '';
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $params['duration'] = (int)$params['duration'] * 60;
                $params['startTime'] = strtotime($params['startTime']);
                $params['link_url'] = trim($params['link_url']);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

                    $result = $row->allowField(true)->save($params);
                    $tArr = $tmodel->getTicketByActId($params['id'],Ticket::TICKET_TYPE_1);//查找活动下的入场卷
                    $tnArr = [];
                    if(!empty($params['ticket_name']) || !empty($params['ticket_price'])){//添加入场卷
                        $count = count($params['ticket_name']);
                        if($count == 0){
                            $count = count($params['ticket_price']);
                        }
                        for($i = 0;$i < $count;$i++){
                            if($params['ticket_price'][$i]==0 || $params['ticket_price'][$i]==0.00){
                                $params['ticket_name'][$i] = 'VIP入场券';
                            }

                            if(!empty($params['ticket_id'][$i])){//获取到入场卷id则更新
                                $rs = $tmodel->findId($params['ticket_id'][$i]);
                                if($rs){
                                    $u[]=[
                                        'id' =>$params['ticket_id'][$i],
                                        'name'=>$params['ticket_name'][$i],
                                        'price'=>priceyuantofen($params['ticket_price'][$i]),
                                        'number'=>$params['ticket_number'][$i],
                                        'activity_id'=>$params['id'],
                                        'type'=>Ticket::TICKET_TYPE_2,
                                        'admin_id'=>$this->auth->id,
                                        'updateTime' => date('Y-m-d H:i:s',time())
                                    ];
                                    $tnArr[] = $params['ticket_id'][$i];//只获取查找到的入场卷id
                                }
                            }else{
                                $t[] = [
                                    'name'=>$params['ticket_name'][$i],
                                    'price'=>priceyuantofen($params['ticket_price'][$i]),
                                    'number'=>$params['ticket_number'][$i],
                                    'activity_id'=>$params['id'],
                                    'type'=>Ticket::TICKET_TYPE_2,
                                    'admin_id'=>$this->auth->id,
                                    'createTime' => date('Y-m-d H:i:s',time())
                                ];
                            }
                        }

                        if(isset($t)){//批量插入
                            $tmodel->insetAll($t);
                        }
                        if(isset($u)){//批量更新
                            $tmodel->updataAll($u);
                        }
                    }

                    if(!empty($tArr)){//查找俩数组中不同元素
                        $tmodel->delAll($tArr,$tnArr);
                    }
                    Db::commit();
                    unset($u);
                    unset($t);
                    unset($tArr);
                    unset($tnArr);

                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

}
